import logging
import pymysql
from django.http import JsonResponse, HttpResponse
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from .sqlmap import *
from django.db import connection

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def update_password(params):
    dict = {
        "user_id": "user_id",
        "password": "password"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210)
    sql = UserSqlMap.update_password.format(**params)
    result = mysql_tools.execute_sql(sql, msg="用户名或密码参数有误", commit=True)
    if isinstance(result, JsonResponse):
        return result
    return success_response()


def check_message(params):
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql = UserSqlMap.check_message.format(**params)
    result = mysql_tools.select_one(sql)
    if not result:
        return success_response({})
    result["join_army"] = int.from_bytes(result["join_army"], byteorder='big')
    result["have_contagion"] = int.from_bytes(result["have_contagion"], byteorder='big')
    result["join_ncms"] = int.from_bytes(result["join_ncms"], byteorder='big')
    result["job_time"] = str(result["job_time"])
    result["regular_time"] = str(result["regular_time"])
    if result["job_time"]: result["job_time"] = result["job_time"].split(" ")[0]
    if result["regular_time"]: result["regular_time"] = result["regular_time"].split(" ")[0]
    if result.get("img_path"):
        result["img_path"] = "static/image/" + result["img_path"]
    return success_response(result)


def edit_message(params):
    dict = {
        "user_id": "user_id",
        "user_tel": "user_tel",
        "address": "address"
    }
    null_params = {
        "attach_id": "attach_id"
    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    if params.get("attach_id"):
        sql_check_attach = UserSqlMap.CHECK_ATTACH.format(**params)
        CHECK_ATTACH = mysql_tools.select_one(sql_check_attach)
        params["img_path"] = CHECK_ATTACH.get("attachment_name")
        UPDATE_HUM = UserSqlMap.UPDATE_HUM.format(**params)
        humance_result = mysql_tools.execute_sql(UPDATE_HUM, commit=True)
        if isinstance(humance_result, JsonResponse):
            return humance_result
    else:
        params["attach_id"] = None
    sql = UserSqlMap.edit_message
    for key, val in params.items():
        if key in ["attach_id", "user_id"]:
            continue
        sql += "%s='{%s}'," % (key, key)
    sql = sql[0:-1]
    sql += " where user_id={user_id}"
    edit_message = sql.format(**params)
    result = mysql_tools.execute_sql(edit_message, commit=True)
    if isinstance(result, JsonResponse):
        return result
    return success_response()


@format_response
def index(request):
    return com_views(request, {
        "update_password": update_password,
        "check_message": check_message,
        "edit_message": edit_message
    })
